package com.sdt.security04.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * @author : fujc-dev@qq.com
 * @created : 2022/10/24 11:26
 */

@Service
public class MyUserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {


        //通过PasswordEncoderFactories可以查看密码要求
        //noop
        //官方推荐使用bcrypt
        //方式1：不建议这么写，因为Spring Security要求我们需要主动定义密码编码器。
        //String password = BCrypt.hashpw("123456", BCrypt.gensalt());
        //UserDetails userDetails = new User("zhangsan", "{bcrypt}" + password, AuthorityUtils.commaSeparatedStringToAuthorityList("admin,user"));

        //方式2：工作中最常用的方式，后面可以连数据库，进行封装
        UserDetails userDetails = new User("fujc", passwordEncoder.encode("123456"), AuthorityUtils.commaSeparatedStringToAuthorityList("admin,user"));

        // 方式3：不将MyUserDetailsServiceImpl交给Spring管理，去掉注解@Service，重写WebSecurityConfigurerAdapter的userDetailsServiceBean。
        /**
         *     @Bean
         *     @Override
         *     public UserDetailsService userDetailsServiceBean() throws Exception {
         *         return new MyUserDetailsServiceImpl();
         *     }
         */
        //方式4：使用protected void configure(AuthenticationManagerBuilder auth) 。具体参见WebSecurityConfig的代码。

        //方式5：使用protected void configure(AuthenticationManagerBuilder auth) 添加UserDetailsService方式。具体参见WebSecurityConfig的代码
        return userDetails;
    }

}
